const express = require('express');
const router = express.Router();

const DBHelper = require('./DBHelper');
const sql = require('./sqlMap');

const cheerio = require("cheerio")
const http = require('http')
const iconv = require('iconv-lite');
const BufferHelper = require('bufferhelper')

// 增加用户
router.post('/addUser', (req, res) => {
  let sql1 = 'select name from user where name =?';
  let sqlStr = sql.user.add; //mysql添加语句
  let params = req.body;
  // console.log(req.body)
  let conn = new DBHelper().getConn(); //数据库调用
  conn.query(sql1, [params.name], (err, result) => {
    if (err) {
      res.json(err);
      return;
    }
    if (result == '') {//判断表中是否有用户
      conn.query(sqlStr, [params.name, params.age, params.password, params.phonenum], (err, results) => {
        if (err) {
          res.json(err);
        } else {
          console.log(results)
          res.json({mess: '注册成功'});
        }
      });
      conn.end();
      return;
    }
    res.json({mess: '用户已存在'});
  });
});

// 查询用户
router.post('/selectUser', (req, res) => {
  // let sqlStr = 'select * from user where name = "'+name+'"' ;
  // let sqlStr = 'select * from user where name ="'+name+'" and age = "'+age+'"' ;
  let sqlStr = sql.user.select;
  console.log(req.body.name)
  let params = req.body;
  let conn = new DBHelper().getConn();
  conn.query(sqlStr, [params.name], (err, result) => {
    if (err) {
      res.json(err);
    } else {
      res.json(result)
      var message = JSON.stringify(result)
      message = JSON.parse(message)
      // res.json({xix:100});
      // res.send({xixixiix:100})
      // console.log(message[0].id)
      // res.status(404).send()
    }
  });
  conn.end();
});

//查询全部用户
router.post('/selectmess', (req, res) => {
  var sql;
  if (req.body.name == '') {
    // sql = 'select * from user limit 3' //限制三条
    sql = 'select * from user'
  } else {
    sql = 'select * from user where name = "' + req.body.name + '"';
  }
  let connection = new DBHelper().getConn()
  connection.query(sql, [req.body.name], (err, result) => {
    if (err) {
      res.json(err)
    } else {
      if (result == '') {
        console.log('123')
        res.status(500);
        return;
      }
      res.json(result)
    }
  })
})

//用户登录
router.post('/Userlogin', (req, res) => {
  let sqlStr = sql.user.login;
  let params = req.body;
  // console.log(req)
  let connect = new DBHelper().getConn()

  connect.query(sqlStr, [params.name, params.password], (err, result) => {
    if (err) {
      res.json(err);
    } else {
      // if(result == ''){
      //   console.log("账号或者密码错误",result)
      //   // res.sendStatus(500);
      //   console.log(res)
      //   // res.status(500).send('Sorry, we cannot find that!');
      //   return;
      // }
      // res.json(result)
      var message = JSON.stringify(result);
      message = JSON.parse(message)
      if (message == '') {
        var sql = 'select * from user where name=?'
        connect.query(sql, [params.name], (err, result1) => {
          if (err) {
            res.json(err);
          } else if (result1 == '') {
            res.json({mess: '用户不存在'})
            console.log(result1)
          } else {
            //做验证次数处理
            res.json({mess: '账号或者密码错误'})
          }
        });
        return;
      }
      res.json({mess: '登录成功'})
      connect.end();
    }
  });
});

//删除用户
router.post('/Deleteuser', (req, res) => {
  let sqlStr = sql.user.deletes;
  let params = req.body;
  let connect = new DBHelper().getConn()
  connect.query(sqlStr, [params.name, params.age], (err, result) => {
    if (err) {
      res.json(err);
    } else {
      if (result == '') {
        res.end("0")
        return;
      }
      res.json(result)
    }
  })
  connect.end();
});

//修改用户信息
router.post('updateUser', (req, res) => {
  let sql = '';
  let params = req.body;
  let connection = new DBHelper().getConn();
  // connection.query(sql,[params])
})

/*
* 测试*/


var data = []
var i = 0
var ele
var $
var nextUrl
var url = 'http://detail.zol.com.cn/convenienttravel/hangzhou/#list_merchant_loc';
// var url = 'http://detail.zol.com.cn/Convenienttravel/index1228429.shtml';
var urlRoot = "http://detail.zol.com.cn"

router.get('/test', function (req, res) {
  nice(url)
  /*  await http.get(url,function(resp){
      var bufferHelper = new BufferHelper();
      resp.on('data', function (chunk) {
        bufferHelper.concat(chunk);
      });
      resp.on('end',function(){
        var app = iconv.decode(bufferHelper.toBuffer(),'GBK')
        var $ = cheerio.load(app);
        // 获取当前页所有电瓶车的a标签
        var ele = $("#J_PicMode a.pic")
        // 存放已经爬取过的url，防止重复爬取
        var urlall= []
        // var data = []
        // var num = 0
        if(ele.length!=0) {
          //拿到所有a标签地址之后，爬取数据
          for (let i = 0; i < ele.length; i++) {
            var URLS = urlRoot+$(ele[i]).attr('href')
            comm(URLS);
           /!* http.get(urlRoot + $(ele[i]).attr('href'), function (response) {
              var buffers = new BufferHelper();
              response.on('data', function (chunks) {
                buffers.concat(chunks)
              });
              response.on('end', function () {
                var comhtml = iconv.decode(buffers.toBuffer(), 'GBK')
                let $2 = cheerio.load(comhtml, {decodeEntities: false})
                // old_urls.push(comhtml)
                data.push({
                  name: $2(".product-model__name").text(),
                  price: $2(".price-type").text(),
                  link: $2(".section-more").attr('href')
                })
                num++;
                console.log(data, 'num', num)
              })
            })*!/
          }
        }
       /!* if(num>ele.length)
        var nextURL = urlRoot + $(".next").attr('href')
        if(nextURL){
          comm(nextURL);
        }*!/
      });
    })*/
})

function nice(url) {
  http.get(url, function (resp) {
    var bufferHelper = new BufferHelper();
    resp.on('data', function (chunk) {
      bufferHelper.concat(chunk);
    });
    resp.on('end', function () {
      var app = iconv.decode(bufferHelper.toBuffer(), 'GBK')
      $ = cheerio.load(app);
      // 获取当前页所有电瓶车的a标签
      ele = $("#J_PicMode a.pic")
      nextUrl = urlRoot + $(".next").attr('href')
      comm(i)

    });
  })
}

function comm(i) {
  if (i < ele.length) {
    var URLS = urlRoot + $(ele[i]).attr('href')
    http.get(URLS, function (response) {
      var buffers = new BufferHelper();
      response.on('data', function (chunks) {
        buffers.concat(chunks)
      });
      response.on('end', function () {
        var comhtml = iconv.decode(buffers.toBuffer(), 'GBK')
        let $2 = cheerio.load(comhtml, {decodeEntities: false})
        data.push({
          name: $2(".product-model__name").text(),
          price: $2(".price-type").text(),
          link: $2(".section-more").attr('href')
        })
        i++;
        console.log(data, 'num', i)
        comm(i)
      })
    })
  } else {
    i = 0;
    if (nextUrl) {
      nice(nextUrl)
      return data;
    }
    else {
      console.log('结束')
    }
  }
}

module.exports = router;
